<template>
  <div id="content" :style="{height:contentHeight+'px'}">
    <div v-show="showModule === 1">
      <Card class="r-n-fs-c">
        <Select style="width: 240px;" v-model="page.projectId" clearable @on-change="searchPipeline" placeholder="所属项目">
          <Option v-for="item in projectList" :key="item.id" :value="item.id">{{item.projectName}}</Option>
        </Select>
        <Select style="width: 240px;margin-left: 5px;" v-model="searchKey" @on-clear="searchKeyClear" placeholder="精确匹配查询参数">
          <Option v-for="item in searchParamList" :key="item.key" :value="item.key">{{item.show}}</Option>
        </Select>
        <Input v-model="searchValue" placeholder="请输入查询内容..." clearable style="width: 300px;margin-left: 5px;" />
        <Button @click="selectPageList(page)" type="primary" style="width: 100px;margin-left: 5px;">查询</Button>
        <Upload
            style="display: inline-block;padding-left: 5px"
            paste
            name="file"
            :headers="headers"
            :format="['json','kml']"
            :show-upload-list="false"
            :before-upload="pipelineLoadBefore"
            :on-format-error="pipelineLoadFormatError"
            :on-error="pipelineLoadError"
            :action="host + url.pipeline_load">
          <Button type="primary" class="r-n-c-c" :style="{width:'150px',lineHeight:'36px'}">管线导入[KML]
            <div style="width: 24px;height:30px;line-height: 30px;display:inline-block;font-size:13px!important;text-align:center;"
                 class="iconfont icon-yulan"></div>
          </Button>
        </Upload>
      </Card>
      <Divider/>
      <Table id="card-list-info-table" class="table" stripe
             border
             show-header
             highlight-row
             :loading="isLoading"
             :columns="tableColumns"
             :data="dataList">
      </Table>
      <Divider/>
      <Card style="margin-bottom: 15px;">
        <Page class="r-w-c-c"
              style="width: 100%"
              class-name="card-list-info-page"
              :total="page.total"
              :current="page.pageNum"
              :page-size="page.pageSize"
              @on-change="onPageChange"
              @on-page-size-change="onPageSizeChange"
              show-elevator
              show-sizer
              show-total/>
      </Card>
    </div>
    <div v-show="showModule === 2" id="pipelineMap" :style="{height:contentHeight-30+'px'}">
      <Button type="default" v-show="backBtnShow" @click="returnPipelineList" style="position: absolute;right: 10px;top: 10px;z-index: 1000">返回管线列表</Button>
    </div>
    <Modal v-model="isUpdatePipelineNameShow" :title="modalTitle">
      <Form ref="selectFormRule" :rules="ruleValidate" :model="selectForm"
            style="margin-left: 0;width: 100%;">
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">管线名称</span>
          <FormItem prop="pipelineName">
            <Input placeholder="管线名称" v-model="selectForm.pipelineName"/>
          </FormItem>
        </label>
      </Form>
      <div slot="footer">
        <Button type="text" @click="isUpdatePipelineNameShow=false">取消</Button>
        <Button type="primary" @click="modalOk()">提交</Button>
      </div>
    </Modal>

    <Modal v-model="isUploadPipelineShow0" :title="modalTitle">
      <Form ref="selectFormRule0" :rules="ruleValidate" :model="selectForm"
            style="margin-left: 0;width: 100%;">
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">管线名称</span>
          <FormItem prop="pipelineName">
            <Input placeholder="管线名称" v-model="selectForm.pipelineName"/>
          </FormItem>
        </label>
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">所属项目</span>
          <Select style="width: 100%" v-model="selectForm.projectId" clearable placeholder="所属项目">
            <Option v-for="item in projectList" :key="item.id" :value="item.id">{{item.projectName}}</Option>
          </Select>
        </label>
      </Form>
      <div slot="footer">
        <Button type="text" @click="isUploadPipelineShow0=false">取消</Button>
        <Button type="primary" @click="modalOk()">提交</Button>
      </div>
    </Modal>
    <Modal v-model="isUploadPipelineShow1" :title="modalTitle">
      <Form ref="selectFormRule1" :rules="ruleValidate" :model="selectForm"
            style="margin-left: 0;width: 100%;">
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">所属项目</span>
          <Select style="width: 100%" v-model="selectForm.projectId" clearable placeholder="所属项目">
            <Option v-for="item in projectList" :key="item.id" :value="item.id">{{item.projectName}}</Option>
          </Select>
        </label>
      </Form>
      <div slot="footer">
        <Button type="text" @click="isUploadPipelineShow1=false">取消</Button>
        <Button type="primary" @click="modalOk()">提交</Button>
      </div>
    </Modal>
    <Modal v-model="isKmlModalShow" width="1000" @on-visible-change="closeKmlModal" footer-hide :title="modalTitle">
      <div style="width: 100%;position:relative;overflow: auto;background:#0009;" :style="{maxHeight:contentHeight-120+'px',width:'inherit'}">
        <div id="kml-map" :style="{height:contentHeight-120+'px',width:'100%'}"></div>
        <div class="r-n-sb-c kml-line-item" style="top:5px;padding: 0 10px;" v-if="kmlDataList.length > 1">
          <div @click="selectMultiItem(kmlMultiSelected)" class="r-n-c-c" :class="kmlMultiSelected ? 'iconfont icon-xuanze kml-line-selected':'kml-line-selected0'"></div>
          <div class="kml-line-seq" style="background:#0000;width: 26px">序号</div>
          <div class="item-edr-fill kml-line-name" style="background:#0000;color: #FFFFFF" >线路名称</div>
          <div class="kml-line-upload iconfont icon-wenjianshangchuan" @click="uploadAllKmlLine" style="width: 60px;background:#0000;">上传</div>
        </div>
        <div class="kml-line-item" :style="{top: kmlDataList.length > 1 ? '35px':'5px',maxHeight: kmlDataList.length > 1 ? (contentHeight - 160)+'px':(contentHeight - 130)+'px'}">
          <div class="r-n-sb-c" :data-kml-ms-id="item.seq" v-for="(item,index) in kmlDataList" :key="item.seq">
            <div @click="selectItem(index)" v-if="kmlDataList.length > 1" class="r-n-c-c" :class="item.selected ? 'iconfont icon-xuanze kml-line-selected':'kml-line-selected0'"></div>
            <div @click="renderKmlLine(item)" class="kml-line-seq">{{item.seq}}</div>
            <div class="item-edr-fill kml-line-name" @click="renderKmlLine(item)">{{ item.name !== undefined ? item.name : '-' }}</div>
            <div class="kml-line-upload iconfont icon-wenjianshangchuan" @click="uploadKmlLine(item)"></div>
          </div>
          <div class="r-n-c-c" v-if="kmlDataList.length === 0">未解析到管线</div>
        </div>
      </div>
    </Modal>
    <Modal v-model="modalTip" width="360">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>操作确认</span>
      </p>
      <div style="text-align:center">
        <p>{{ modalTipContent }}</p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long :loading="modalLoading" @click="modalTipOk">确认操作</Button>
      </div>
    </Modal>
  </div>
</template>

<script>

import {mapGetters, mapState} from "vuex"
import axios from "axios";
import {LeafLetMap} from "@/global/mapConfig";
import {mapUrl, Request} from "@/global/config";

export default {
  name: "Pipeline",
  computed: {
    ...mapState(["url", "host", "resourceHost", "realSideWidth","projectList"]),
    ...mapGetters(["contentWidth", "contentHeight"]),
  },
  data() {
    return {
      isKmlModalShow: false,
      isUploadPipelineShow1: false,
      isUploadPipelineShow0: false,
      isUpdatePipelineNameShow: false,
      backBtnShow: false,
      searchKey: 'name',
      showModule: 1,
      searchValue: null,
      btnLoading: false,
      isLoading: false,
      modalTip: false,
      modalTipContent: null,
      modalLoading: false,
      isFileAnalyseModalShow: false,
      isPageSizeChanging: false,
      uploadPipelineFileName: null,
      uploadPipelineFile: null,
      modalTitle: '管线上传',
      modalTitleData: null,
      operatorType: ['管线上传','管线修改','管线禁用','管线解禁','管线删除'],
      ruleValidate: {
        pipelineName: [
          {required: true, type: 'string', message: '管线名称不能为空', trigger: 'change'},
          { min: 2, message: '管线名称不能少于2个字符', trigger: 'change'},
          { max: 20, message: '管线名称不能超过20个字符', trigger: 'change'}
        ]
      },
      headers: {
        'u-projectId': null,
        'u-uid': null,
        'u-token': null,
      },
      selectForm: {
        id: null,
        file: null,
        state: null,
        pipelineName: null,
        pipelineData: null,
        projectId: null
      },
      page:{
        total: 0,
        pageSize: 10,
        pageNum: 1,
        descParams:'id',
        id: null,
        name: null,
        projectId: null,
      },
      tableColumns: [
        {
          title: '管线ID',
          key: 'id',
          width: 100,
          minWidth: 100,
          resizable: true,
          align: "center",
          ellipsis: true,
          sortable: true,
        },
        {
          title: '管线名称',
          key: 'name',
          resizable: true,
          minWidth: 180,
          align: "center"
        },
        {
          title: '中心点',
          key: 'centerPoint',
          resizable: true,
          width: 300,
          minWidth: 240,
          align: "center",
        },
        {
          title: '状态',
          key: 'state',
          resizable: true,
          minWidth: 80,
          align: "center",
          render:function(createElement, data) {
            let {state} = data.row;
            if (state === 0) {
              return createElement('Tooltip',{
                attrs: {
                  content :"可用",
                  placement : "top"
                }
              },[createElement('div',{
                style: {
                  height:'15px',
                  width:'15px',
                  borderRadius:'50%',
                  background: '#1afa29'
                }
              },'')]);
            }
            if (state === 1) {
              return createElement('Tooltip',{
                attrs: {
                  content :"禁用",
                  placement : "top"
                }
              },[createElement('div',{
                style: {
                  height:'15px',
                  width:'15px',
                  borderRadius:'50%',
                  background: '#f74242'
                }
              },'')]);
            }
          },
        },
        {
          title: '管线PB文件',
          key: 'pointsUrl',
          resizable: true,
          width: 180,
          minWidth: 150,
          align: "center",
          render: function (createElement,data){
            let {pointsUrl} = data.row;
            if (pointsUrl === null){
              return createElement('span','-');
            }
            return createElement('Tooltip',{
              attrs: {
                content : pointsUrl,
                placement : "top",
                style: {
                  width: '100%'
                }
              }
            },[createElement('div',pointsUrl.substring(pointsUrl.lastIndexOf("/")+1))]);
          }
        },
        {
          title: '所属项目',
          key: 'projectId',
          resizable: true,
          width: 180,
          align: "center",
          render: Request.projectNameRender
        },
        {
          title: '操作',
          resizable: true,
          minWidth: 420,
          align: "center",
          render: this.operatorRenderFunction
        }
      ],
      kmlColumns: [
        {
          title: '序号',
          key: 'seq',
          width: 85,
          minWidth: 100,
          resizable: true,
          align: "center",
          ellipsis: true,
          sortable: true,
        },
        {
          title: '名称',
          key: 'name',
          minWidth: 200,
          resizable: true,
          align: "center",
          ellipsis: true,
          render:function (createElement, data) {
            let {name} = data.row;
            if (name === undefined){
              return createElement('span','-')
            }
            return createElement('span',name)
          }
        },
        {
          title: '操作',
          resizable: true,
          minWidth: 210,
          align: "center",
          render: this.operatorRenderFunction2
        }
      ],
      dataList: [],
      kmlMultiSelected: false,
      kmlDataList: [],
      searchParamList: [
        {
          key: "name",
          show: "管道名称",
        }
      ],
      pipelineMap: null,
      kmlMap: null,
      kmlRenderLine: null,
      kmlRenderLineId: null,
      mapSource: mapUrl.ArcGIS,
      mapLayers: [],
      kmlMapLayers: [],
      currentMs: null
    }
  },
  watch: {

  },
  created: function () {
    this.initSource();
  },
  mounted: function () {
    let self = this;
    this.headers['u-projectId'] = localStorage.getItem('u-projectId');
    this.headers['u-uid'] = localStorage.getItem('u-uid');
    this.headers['u-token'] = localStorage.getItem('u-token');
    self.selectPageList(self.page);
  },
  methods: {
    closeKmlModal(e){
      if (!e){
        if (this.kmlMap !== null && this.kmlRenderLine !== null) {
          this.kmlMap.removeLayer(this.kmlRenderLine);
          this.kmlRenderLine = null;
          this.kmlDataList = [];
        }
      }
    },
    selectMultiItem(selected){
      this.kmlMultiSelected = !selected;
      for (let i in this.kmlDataList) {
        this.kmlDataList[i]['selected'] = this.kmlMultiSelected;
      }
    },
    selectItem(index){
      this.kmlDataList[index]['selected'] = !this.kmlDataList[index]['selected'];
    },
    uploadAllKmlLine(){
      this.isUploadPipelineShow1 = true;
      this.modalTitle = this.operatorType[0];
    },
    uploadKmlLine(data){
      if (this.currentMs !== null){
        let element = document.querySelector(`div[data-kml-ms-id="${this.currentMs['seq']}"]`);
        if (element !== null){
          for (let i = 0; i < element.children.length; i++) {
            if (i !== 0 || element.children.length === 3){
              element.children[i].style.background = "";
            }
          }
        }
      }
      this.currentMs = data;
      let element = document.querySelector(`div[data-kml-ms-id="${data['seq']}"]`);
      for (let i = 0; i < element.children.length; i++) {
        if (i !== 0 || element.children.length === 3){
          element.children[i].style.background = "#d74e4eba";
        }
      }
      this.$refs['selectFormRule0'].resetFields();
      this.$refs['selectFormRule1'].resetFields();

      this.modalTitle = this.operatorType[0];
      this.selectForm.pipelineName = data['name'];
      this.selectForm.pipelineData = data;
      this.isUploadPipelineShow0 = true;
    },
    renderKmlLine(data){
      let self = this;
      if (self.currentMs !== null){
        let element = document.querySelector(`div[data-kml-ms-id="${self.currentMs['seq']}"]`);
        if (element !== null){
          for (let i = 0; i < element.children.length; i++) {
            if (i !== 0 || element.children.length === 3){
              element.children[i].style.background = "";
            }
          }
        }
      }
      self.currentMs = data;
      let element = document.querySelector(`div[data-kml-ms-id="${data['seq']}"]`);
      for (let i = 0; i < element.children.length; i++) {
        if (i !== 0 || element.children.length === 3){
          element.children[i].style.background = "#d74e4eba";
        }
      }
      let sleepTime = (500/data['line'].length).toFixed(5);
      self.kmlRenderLineId = data['seq'];
      let currentSeq = data['seq'];
      if (this.kmlMap !== null){
        if (this.kmlRenderLine !== null){
          this.kmlMap.removeLayer(this.kmlRenderLine);
          this.kmlRenderLine = null;
        }
        self.kmlRenderLine = self.kmlMap.renderInspectLine(data['line'],{
          type: 'line',
          color: '#FF6700',
          opacity: 0.7,
          weight: 5
        });
        // drawLine();
      }
      function drawLine() {
        (async ()=>{
          for (let point of data['line']) {
            if (currentSeq === self.kmlRenderLineId){
              doDrawLine(point['lat'],point['lng']);
              await sleep(sleepTime);
            }
          }
        })();
      }
      function doDrawLine(lat,lng){
        if (self.kmlRenderLine === null){
          self.kmlRenderLine = self.kmlMap.renderInspectLine([[lat,lng]],{
            type: 'line',
            color: '#FF6700',
            opacity: 0.7,
            weight: 5
          });
        }else {
          self.kmlRenderLine.addLatLng([lat,lng]);
          self.kmlMap.map.addLayer(self.kmlRenderLine);
          self.kmlMap.map.fitBounds(self.kmlRenderLine.getBounds());
        }
      }
      function sleep (time) {
        return new Promise((resolve) => setTimeout(resolve, time));
      }
    },
    searchPipeline(){
      this.page.pageNum = 1;
      this.selectPageList(this.page)
    },
    initSource(){
      let ms = localStorage.getItem('mapSource');
      if (ms !== undefined && ms !== null){
        this.mapSource = mapUrl[ms];
      }
    },
    returnPipelineList(){
      this.showModule = 1;
      this.backBtnShow = false;
      if (this.pipelineMap !== null){
        this.pipelineMap.map.remove();
        this.pipelineMap = null;
      }
    },
    modalOk(){
      this.selectForm.file = this.uploadPipelineFile;
      let isValidate = false;
      if (this.selectForm.projectId === null){
        isValidate = false;
        this.$Message.error('所属项目未选择...');
        return;
      }
      this.$refs['selectFormRule'].validate((valid) => {
        if (valid) {
          isValidate = true;
        }
      })
      if (this.modalTitle === this.operatorType[0]){
        if (this.isUpdatePipelineNameShow){
          if (this.uploadPipelineFile === null){
            isValidate = false;
            this.$Message.error('文件未选择...');
            return;
          }
        }
        if (this.isUpdatePipelineNameShow || this.isUploadPipelineShow0){
          if (!isValidate) {
            return;
          }
          this.isUpdatePipelineNameShow ? this.insertPipeline(this.selectForm) : this.insertPipeline2(this.selectForm);
        }
        if (this.isUploadPipelineShow1){
          this.insertPipeline2(this.selectForm);
        }
      }else if (this.modalTitle === this.operatorType[1]){
        if (!isValidate) {
          return;
        }
        this.isUpdatePipelineNameShow = !isValidate;
        this.updatePipeline(this.selectForm);
      }
    },
    pipelineUploadBefore(e){
      this.uploadPipelineFile = e;
      this.uploadPipelineFileName = e.name;
      this.selectForm.pipelineName = e.name.substring(0,e.name.lastIndexOf("."));
      return false;
    },
    pipelineLoadBefore(file) {
      let self = this;
      self.kmlDataList = [];
      if (self.kmlMap === null){
        setTimeout(()=>{
          self.kmlMap = new LeafLetMap(document.getElementById('kml-map'),self.mapSource);
        },200);
      }
      if (self.kmlMap !== null && self.kmlMapLayers.length !== 0){
        self.kmlMapLayers.forEach( layer =>{
          self.kmlMap.removeLayer(layer);
        });
      }
      if (file.name.endsWith('.kml')){
        self.$Spin.show();
        let reader = new FileReader();
        reader.readAsText(file);
        reader.onload = function(e){
          let result = e.target.result;
          if (result !== undefined){
            let options = {
              attributeNamePrefix : "@_",
              ignoreAttributes: false,
            };
            let jsonObj = self.xmlParser.parse(result, options);
            let seq = 1;
            let dataArray = [];
            function recursionParserObj(jsonObj,labelName) {
              self._.forIn(jsonObj,(v,k)=>{
                if (k === 'Document' || k === 'Placemark' || k === 'Folder'){
                  if (self._.isArray(v)){
                    recursionParserArray(v)
                  }
                }
                if (k === 'LineString'){
                  if (v !== undefined && v['coordinates'] !== undefined){
                    let lineString = v['coordinates'];
                    lineString = lineString.replaceAll(/\s+/g,' ');
                    let lineStringArray = lineString.split(" ");
                    let linePointArray = [];
                    let seq0 = 1;
                    self._.forEach(lineStringArray,(v)=> {
                      let point = v.split(",");
                      linePointArray.push({
                        lng: point[0],
                        lat: point[1],
                        alt: point[2],
                        seq: seq0++
                      })
                    })
                    dataArray.push({
                      selected: false,
                      seq: seq++,
                      name: labelName,
                      line: linePointArray
                    })
                  }
                }
                if (k === 'Polygon'){
                  if (v['outerBoundaryIs'] !== undefined){
                    if (v['outerBoundaryIs'] !== undefined && v['outerBoundaryIs']['LinearRing'] !== undefined &&
                        v['outerBoundaryIs']['LinearRing']['coordinates'] !== undefined){
                      let outerPolygon = v['outerBoundaryIs']['LinearRing']['coordinates'];
                      outerPolygon = outerPolygon.replaceAll(/\s+/g,' ');
                      let polygonStringArray = outerPolygon.split(" ");
                      let polygonPointArray = [];
                      self._.forEach(polygonStringArray,(v)=> {
                        let point = v.split(",");
                        polygonPointArray.push({
                          lng: point[0],
                          lat: point[1],
                          alt: point[2],
                        })
                      })
                    }
                  }
                }
                if (k === 'Point'){
                  if (v['coordinates'] !== undefined){
                    let pointArray = v['coordinates'].split(",");
                    let point = {
                      lng: pointArray[0],
                      lat: pointArray[1],
                      alt: pointArray[2]
                    }
                  }
                }
                if (self._.isPlainObject(v)){
                  recursionParserObj(v,v['name'])
                }
              })
            }
            function recursionParserArray(jsonArray) {
              self._.forEach(jsonArray,(v)=>{
                if (self._.isPlainObject(v)){
                  recursionParserObj(v,v['name'])
                }
                if (self._.isArray(v)){
                  recursionParserArray(v)
                }
              })
            }
            recursionParserObj(jsonObj,'kml');
            self.$Spin.hide();
            self.isKmlModalShow = true;
            self.kmlDataList = dataArray;
          }
        }
      }
      if (file.name.endsWith('.json')){
        self.$Spin.show();
        let reader = new FileReader();
        reader.readAsText(file);
        reader.onload = function(e){
          let result = e.target.result;
          if (result !== undefined){
            let seq = 1;
            let dataArray = [];
            let lineJson = JSON.parse(result);
            lineJson.forEach( item => {
              if (item['line'] !== undefined && item['line'] !== null){
                for (let i = 0; i < item['line'].length; i++) {
                  item['line'][i]['lng'] = Number.parseFloat(item['line'][i]['lng'].toFixed(7));
                  item['line'][i]['lat'] = Number.parseFloat(item['line'][i]['lat'].toFixed(7));
                  if (item['line'][i]['alt'] !== undefined){
                    item['line'][i]['alt'] = Number.parseFloat(item['line'][i]['alt'].toFixed(7));
                  }else {
                    item['line'][i]['alt'] = 0;
                  }
                  item['line'][i]['seq'] = i+1;
                }
              }
              dataArray.push({
                name: item['name'],
                line: item['line'],
                selected: false,
                seq: seq++,
              })
            })
            self.$Spin.hide();
            self.isKmlModalShow = true;
            self.kmlDataList = dataArray;
          }
        }
      }
      return false;
    },
    pipelineLoadFormatError(file) {
      this.$Spin.hide();
      this.$Notice.warning({
        title: '管线文件格式错误',
        desc: '管线文件 ' + file.name + ' 格式不正确，请上传 JSON 或 KML 格式文件！',
        duration: 10
      });
    },
    pipelineLoadError() {
      this.$Spin.hide();
      this.$Notice.error("管线加载失败...")
    },
    searchKeyClear(){
      let self = this;
      self.searchValue = null;
    },
    onPageChange(changedPage) {
      this.page.pageNum = changedPage;
      !this.isPageSizeChanging ? this.selectPageList(this.page) : {};
    },
    onPageSizeChange(changedPageSize) {
      this.isPageSizeChanging = true;
      new Promise(resolve => {
        this.page.pageSize = changedPageSize;
        resolve(changedPageSize)
      }).then(() => {
        this.selectPageList(this.page);
        this.isPageSizeChanging = false;
      })
    },
    modalTipOk() {
      this.modalLoading = true;
      switch (this.modalTitle){
        case this.operatorType[2]:{
          this.modalLoading = false;
          this.modalTip = false;
          this.updatePipeline(this.selectForm);
        }break;
        case this.operatorType[3]:{
          this.modalLoading = false;
          this.modalTip = false;
          this.updatePipeline(this.selectForm);
        }break;
        case this.operatorType[4]:{
          this.modalLoading = false;
          this.modalTip = false;
          this.deletePipeline(this.selectForm);
        }break;
      }
    },
    operatorRenderFunction2(createElement, data) {
      let self = this;
      let {seq,line} = data.row;
      let btnList = [];
      btnList.push(createElement('Button', {
        'class': 'button-item',
        style: {
          width: '80px',
          border: '#5CADFF 1px dashed',
          color: '#5cadff'
        },
        attrs: {
          type: "dashed"
        },
        nativeOn: {
          click: function () {

          }
        },
      }, '预览'));
      btnList.push(createElement('Button', {
        'class': 'button-item',
        style: {
          width: '80px',
          border: '#5CADFF 1px dashed',
          color: '#5cadff'
        },
        attrs: {
          type: "dashed"
        },
        nativeOn: {
          click: function () {

          }
        },
      }, '导入'));
      return createElement("div", {'class': 'r-n-c-c'}, [
        createElement('ButtonGroup', btnList),
      ])
    },
    operatorRenderFunction(createElement, data) {
      let self = this;
      let {
        id,name,state,projectId
      } = data.row;
      let btnList = [];
      btnList.push(createElement('Button', {
        'class': 'button-item',
        style: {
          width: '100px',
          border: '#5CADFF 1px dashed',
          color: '#5cadff'
        },
        attrs: {
          type: "dashed"
        },
        nativeOn: {
          click: function () {
            self.showModule = 2;
            self.$Spin.show({
              render: (h) => {
                return h('div', [
                  h('Icon', {
                    'class': 'demo-spin-icon-load',
                    props: {
                      type: 'ios-loading',
                      size: 18
                    }
                  }),
                  h('div', 'Loading')
                ])
              }
            });
            axios.get(self.url.pipeline_details + id).then(function (response) {
              self.$Spin.hide();
              if (self.pipelineMap === null){

                self.pipelineMap = new LeafLetMap(document.getElementById("pipelineMap"),self.mapSource);
              }
              if (self.pipelineMap !== null && self.mapLayers.length !== 0){
                self.mapLayers.forEach( layer =>{
                  self.pipelineMap.removeLayer(layer);
                });
              }
              let {points} = response.data.content;
              if (self.pipelineMap !== null){
                let renderInspectLine = self.pipelineMap.renderInspectLine(points,{
                  type: 'line',
                  color: '#FF6700',
                  opacity: 0.7,
                  weight: 5
                });
                self.mapLayers.push(renderInspectLine);
              }
              self.backBtnShow = true;
            })
          }
        },
      }, '地图展示'));
      btnList.push(createElement('Button', {
        'class': 'button-item',
        style: {
          width: '100px',
          border: '#5CADFF 1px dashed',
          color: '#5cadff'
        },
        attrs: {
          type: "dashed"
        },
        nativeOn: {
          click: function () {
            self.modalTitle = self.operatorType[1];
            self.selectForm = {
              id: id,
              file: null,
              state: null,
              pipelineName: name,
              projectId: projectId
            }
            self.isUpdatePipelineNameShow = true;
          }
        },
      }, '名称修改'));
      if (state === 0){
        btnList.push(createElement('Button', {
          'class': 'button-item',
          style: {
            width: '80px',
            border: '#5CADFF 1px dashed',
            color: '#fa7501'
          },
          attrs: {
            type: "dashed"
          },
          nativeOn: {
            click: function () {
              self.modalTitle = self.operatorType[2];
              self.modalTipContent = `将要禁用项目[${projectId}]的管线[${name}],是否继续?`;
              self.selectForm = {
                id: id,
                file: null,
                state: 1,
                pipelineName: null,
                projectId: projectId
              }
              self.modalTip = true;
            }
          },
        }, '禁用'));
      }else if (state === 1){
        btnList.push(createElement('Button', {
          'class': 'button-item',
          style: {
            width: '80px',
            border: '#5CADFF 1px dashed',
            color: '#5cadff'
          },
          attrs: {
            type: "dashed"
          },
          nativeOn: {
            click: function () {
              self.modalTitle = self.operatorType[3];
              self.modalTipContent = `将要解禁项目[${projectId}]的管线[${name}],是否继续?`;
              self.selectForm = {
                id: id,
                file: null,
                state: 0,
                pipelineName: null,
                projectId: projectId
              }
              self.modalTip = true;
            }
          },
        }, '解禁'));
      }
      btnList.push(createElement('Button', {
        'class': 'button-item',
        style: {
          width: '80px',
          border: '#5CADFF 1px dashed',
          color: '#FF6666'
        },
        attrs: {
          type: "dashed"
        },
        nativeOn: {
          click: function () {
            self.modalTitle = self.operatorType[4];
            self.modalTipContent = `将要删除项目[${projectId}]的管线[${name}],是否继续?`;
            self.selectForm = {
              id: id,
              file: null,
              state: null,
              pipelineName: null,
              projectId: null
            }
            self.modalTip = true
          }
        },
      }, '删除'));
      return createElement("div", {'class': 'r-n-c-c'}, [
        createElement('ButtonGroup', btnList),
      ])
    },
    insertPipeline(selectForm){
      let self = this;
      if (self.isUpdatePipelineNameShow || self.isUploadPipelineShow0){
        let form = new FormData();
        form.append("file",selectForm['file'])
        form.append("pipelineName",selectForm['pipelineName'])
        form.append("projectId",selectForm['projectId'])
        this.$Spin.show();
        axios.post(self.url.pipeline_upload, form).then(function (response) {
          let {message, state} = response.data;
          if (state === 200) {
            self.selectPageList(self.page);
            self.$Message.success(message);
          } else {
            self.$Message.error(message);
          }
          self.$Spin.hide();
          self.$refs['selectFormRule'].resetFields();
          self.uploadPipelineFileName = null;
          self.isUpdatePipelineNameShow = false;
          self.isUploadPipelineShow0 = false;
        });
      }
    },
    insertPipeline2(selectForm){
      let self = this;
      if (self.isUploadPipelineShow0 || self.isUploadPipelineShow1){
        let kmlKines = []
        for (let kmlData of this.kmlDataList) {
          if (kmlData['selected']){
            kmlKines.push({
              name : kmlData['name'],
              line : kmlData['line']
            })
          }
        }
        let form = {};
        form.projectId = selectForm['projectId'];
        let line = Object.assign({},selectForm['pipelineData']);
        if (line != null){
          line['name'] = selectForm['pipelineName'];
          delete line['seq'];
          delete line['selected'];
        }
        form.pipelineData = self.isUploadPipelineShow1 ? kmlKines : line;
        form.isMultiple = self.isUploadPipelineShow1;
        this.$Spin.show();
        axios.post(self.url.pipeline_upload2, form).then(function (response) {
          let {message, state} = response.data;
          if (state === 200) {
            self.selectPageList(self.page);
            self.$Message.success(message);
          } else {
            self.$Message.error(message);
          }
          self.$Spin.hide();
          self.$refs['selectFormRule0'].resetFields();
          self.$refs['selectFormRule1'].resetFields();
          self.isUploadPipelineShow0 = false;
          self.isUploadPipelineShow1 = false;
        });
      }
    },
    updatePipeline(selectForm){
      let self = this,{id,pipelineName,projectId,state} = selectForm;
      let form = {};
      form.id = id;
      if (pipelineName !== null){
        form.name = pipelineName;
      }
      if (state !== null){
        form.state = state;
      }
      form.projectId = projectId;
      this.$Spin.show({
        render: (h) => {
          return h('div', [
            h('Icon', {
              'class': 'demo-spin-icon-load',
              props: {
                type: 'ios-loading',
                size: 18
              }
            }),
            h('div', 'Loading')
          ])
        }
      });
      axios.patch(self.url.pipeline_modify, form).then(function (response) {
        let {message, state} = response.data;
        if (state === 200) {
          self.selectPageList(self.page);
          self.$Message.success(message);
        } else {
          self.$Message.error(message);
        }
        self.$Spin.hide();
      }).catch(()=>{
        self.$Spin.hide();
      });
    },
    deletePipeline(selectForm){
      let self = this,{id} = selectForm;
      axios.delete(self.url.pipeline_delete + id).then(function (response) {
        let {message, state} = response.data;
        if (state === 200) {
          self.selectPageList(self.page);
          self.$Message.success(message);
        } else {
          self.$Message.error(message);
        }
        self.$Spin.hide();
      }).catch(()=>{
        self.$Spin.hide();
      });
    },
    selectPageList(selectForm) {
      let self = this;
      let form = Object.assign({}, selectForm);
      if (self.searchKey !== null && self.searchValue !== null && self.searchValue !== ""){
        form[self.searchKey] = self.searchValue.trim();
      }
      self.isLoading = true;
      axios.get(self.url.pipeline_list, {params: form}).then(function (response) {
        let {records,total} = response.data.content;
        self.page.total = total;
        self.dataList = records;
        self.isLoading = false;
      }).catch(function () {
        self.isLoading = false;
      });
    }
  }
}
</script>

<style scoped>
#content {
  background: #FFFFFF;
  padding: 15px;
  overflow: auto;
}

#pipelineMap{
  background: #000;
  border-radius: 5px;
}
.item-input {
  height: 45px;
  line-height: 45px;
  margin-bottom: 10px;
}
.kml-line-item{
  position: absolute;
  left:5px;
  z-index: 10000;
  color: #FFF;
  background: rgba(0, 0, 0, 0) radial-gradient(rgba(0, 0, 0, 0.14), rgba(13, 13, 13, 0.46)) repeat scroll 0% 0%;
  padding: 10px;
  border-radius: 10px;
  width: 300px;
  overflow:auto;
  height: auto
}
.kml-line-name{
  line-height: 24px;
  background: #00000070;
  border-radius: 5px;
  margin: 2px 0;
  font-size: 12px;
  padding: 0 5px;
  text-align: center;
  width: 120px;
  cursor: pointer;
  white-space:nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.kml-line-upload{
  width: 24px;
  height: 24px;
  background:#00000070;
  margin-left: 10px;
  border-radius: 5px;
  line-height: 24px;
  display:inline-block;
  font-size:13px!important;
  text-align:center;
  cursor: pointer;
}
.kml-line-seq{
  width: 24px;
  height: 24px;
  background:#00000070;
  margin-right: 10px;
  border-radius: 5px;
  line-height: 24px;
  display:inline-block;
  font-size:13px!important;
  text-align:center;
  cursor: pointer;
}
.kml-line-selected{
  width: 18px;height: 18px;background:#d74e4eba;margin-right: 10px;border-radius: 5px;
  line-height: 18px;display:inline-block;font-size:12px!important;text-align:center;cursor: pointer;
}
.kml-line-selected0{
  width: 18px;
  height: 18px;
  background: #0003;
  border:solid 1px #00000070;
  margin-right: 10px;
  border-radius: 5px;
  line-height: 18px;
  display:inline-block;
  font-size:12px!important;
  text-align:center;
  cursor: pointer;
}
.item-input-span {
  /*height: inherit;*/
  width: 120px;
}

.item-key {
  /*height: inherit;*/
  width: 150px;
}
.item-value {
  /*height: inherit;*/
  width: 50px;
}

.ivu-form-item-content {
  margin-left: 0 !important;
  position: relative;
  line-height: 32px;
  font-size: 14px;
}

.ivu-form-item {
  margin-bottom: 0;
  width: 100%;
}

.button-item {
  border: #19be6b 1px dashed;
  color: #19be6b;
}

.filter-item {
  margin: 0 5px;
}

.demo-spin-icon-load{
  animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from { transform: rotate(0deg);}
  50%  { transform: rotate(180deg);}
  to   { transform: rotate(360deg);}
}
.demo-spin-col{
  height: 20px;
  position: relative;
}
</style>
